<template>
  <div class="oe-add-exam" v-loading="loading">
    <top-tip
      ref="back"
      v-if="batchTitle || $route.name === 'addExamOne'"
      :batchTitle="batchTitle"
      :examTitle="examTitle"
      :examData="examData"
    ></top-tip>
    <a-steps :current="step" @change="onChange" style="background: #fff; margin-top: 20px; padding: 10px 340px;">
      <a-step v-for="item in current" :key="item.text" :title="item.text" :status="item.status" :description="item.description" />
    </a-steps>
    <component
      :is="currentView"
      :stepMode="true"
      :examid="examid"
      :batchid="batchid"
      :onlyRead="onlyRead"
      :isPublic="isPublic"
      :isHasBK="isHasBK"
      :isQues="isQues"
      :examMode="examMode"
      :sysType="sysType"
    ></component>
    <div
      v-if="step === 2 || step === 3 || (step === 5 && examMode === 0) || (step ===4 && examMode != 0)"
      style="display: flex; justify-content: space-around; padding: 50px 600px; background: #fff"
    >
      <a-button type="primary" @click="previousStep"> 上一步 </a-button>
      <a-button
        type="primary"
        v-if="
          (step === 3 && isStu && isQues && examid && examMode === 0) ||
          (step === 3 && isRoom && examMode === 1) ||
          (step === 4 && isStu && isQues && examid && examMode === 0) ||
          (step === 4 && isRoom && isStu && isQues && examid && examMode === 1)
        "
        @click="nextStep"
      >
        下一步
      </a-button>
    </div>
  </div>
</template>

<script>
import topTip from '@/components/top-tip/index.vue';
import addExam from '@/components/exam/add-exam/index.vue';
import setTestPaper from '@/components/exam/set-test-paper/index.vue';
import studentManage from '@/components/exam/student-manage/index.vue';
import proctorTeacher from '@/components/exam/proctor-teacher/index.vue';
import reviewTeacher from '@/components/exam/review-teacher/index1.vue';
import pushExam from '@/components/exam/push-exam/index.vue';
import roomManagement from '@/components/exam/exam-room/index.vue';
import GetOperationList from '@/lib/mixin/methods.js';
export default {
  name: 'addExamOne',
  mixins: [GetOperationList],
  components: {
    topTip,
    addExam,
    setTestPaper,
    studentManage,
    proctorTeacher,
    reviewTeacher,
    pushExam,
    roomManagement,
  },
  data() {
    return {
      step: 0, //考试步骤
      current: [
        { description: '设置出题人、审核人、分数等考试基本信息', text: '新建考试', status: 'process' },
        { description: '通过随机出题或手动出题等方式设置考题', text: '设置题目', status: 'wait' },
        // { description: '从学生管理按班级或个人选择该考试考生', text: '考生导入', status: 'wait' },
        // { description: '选择批阅教师，客观试卷可不设置批阅教师', text: '批阅教师', status: 'wait' },
        // { description: '规定考试时间、登录方式、监考手段等规则', text: '发布考试', status: 'wait' },
        // { description: '分配考生的监考教师，可不设置监考教师', text: '监考教师', status: 'wait' },
      ],
      loading: false,
      status: 'wait', //点击已完成步骤之前的步骤状态，默认wait
      examMode: 0, //考试方式，0线上，1线下
      saveExamMode: 0, //刚进页面存储的临时考试方式，防止未保存刷新
      examTitle: '',
      batchTitle: '',
      isStu: false, //考生
      isRoom: false, //线下考场
      isQues: false, //题目
      isMarkTea: false, //批阅
      isMonitorTea: false, //监考
      isPublic: false, //发布
      isHasBK: false, //补考
      sysType: 2,
      // 考卷份数
      examData: {
        defaultValue: '',
        paperList: 0,
        repairList: 0,
      },
      operationList: [],
      onlyOnce: false, //进入页面
      onlyRead: false, //编辑考试只读权限
    };
  },
  props: {
    batchid: {
      type: String,
      default: '',
    },
  },
  watch: {
    step() {
      //切换组件滑到最上
      window.scrollTo(0, 0);
      window.pageYOffset = 0;
      document.documentElement.scrollTop = 0;
      document.body.scrollTop = 0;
    },
  },
  computed: {
    examid() {
      if (this.$route.name === 'editExamOne') {
        return this.$route.params.examid;
      } else if (this.$route.name === 'editExamTwo') {
        return this.$route.params.examid;
      }
      return this.$store.state.examid;
    },
    type() {
      return this.$route.name === 'editExamOne' ? '编辑考试' : '新建考试';
    },
    currentView() {
      let current = '';
      console.log('步骤:',this.step);
      switch (this.step) {
        case 0:
          current = 'addExam';
          break;
        case 1:
          current = 'setTestPaper';
          break;
        case 2:
          current = 'studentManage';
          break;
        case 3:
          current = this.examMode === 0 ? 'reviewTeacher' : 'roomManagement';
          break;
        case 4:
          current = this.examMode === 0 ? 'pushExam' : 'reviewTeacher';
          break;
        case 5:
          current = this.examMode === 0 ? 'proctorTeacher' : 'pushExam';
          break;
        default:
          break;
      };
      console.log(this.examMode === 0);
      return current;
    },
  },
  beforeRouteLeave(to, from, next) {
    let _this = this;
    if (this.step === 5) {
      //点击完成按钮之后离开页面
      this.$store.commit('setExamId', '');
      sessionStorage.removeItem('examStep');
      window.onbeforeunload = undefined;
      next();
    } else {
      if (this.$route.name === 'addExamOne') {
        this.$confirm({
          title: '确认要离开新增考试页面?',
          content: '离开不可返回，剩余步骤可在编辑考试页面设置',
          okText: '确认',
          okType: 'danger',
          cancelText: '取消',
          onOk() {
            _this.$store.commit('setExamId', '');
            sessionStorage.removeItem('examStep');
            window.onbeforeunload = undefined;
            next();
          },
          onCancel() {
            next(false);
          },
        });
      } else {
        _this.$store.commit('setExamId', '');
        sessionStorage.removeItem('examStep');
        window.onbeforeunload = undefined;
        next();
      }
    }
  },
  created() {
    //刷新sessionStorage拿数据
    this.$store.commit('setExamId', JSON.parse(sessionStorage.getItem('examStep'))?.examid);
    //刷新之前存sessionStorage
    window.onbeforeunload = (e) => {
      sessionStorage.setItem(
        'examStep',
        JSON.stringify({
          examid: this.examid,
        })
      );
      e = e || window.event;
      // 兼容IE8和Firefox 4之前的版本
      if (e) {
        e.returnValue = '关闭提示';
      }
      // Chrome, Safari, Firefox 3+, Opera 12+ , IE 9+
      return '关闭提示';
    };
    if (this.examid) {
      console.log(123)
      this.getExamInfo();
      this.onlyOnce = true;
    } else {
      console.log(123456789)
      this.getExamList();
      this.getOpeartion();
    }
  },
  methods: {
    getExamList() {
      this.loading = true;
      this.$http
        .post('/api/design/workexam/getExamList', {
          batchId: this.batchid,
        })
        .then((rst) => {
          this.loading = false;
          if (rst.code == 1) {
            this.batchTitle = rst.batchTitle;
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    getOpeartion() {
      this.loading = true;
      this.GetOperationList('examId', this.examid).then((rst) => {
        this.loading = false;
        if (rst.code === 1) {
          this.examTitle = rst.examTitle;
          this.batchTitle = rst.batchTitle ? rst.batchTitle : this.batchTitle;
          this.operationList = [];
          if (rst.list.length) {
            rst.list.forEach((item) => {
              if (item.IsWrite || item.IsRead) {
                item.Name === 'add/edit/del' && !item.IsWrite && (this.onlyRead = true);
                this.operationList.push(item.Name);
              }
            });
            console.log('getOpeartion',this.onlyOnce);
            this.onlyOnce && this.jumpStep();
          }
        } else {
          this.$message.error(rst.msg);
        }
      });
    },
    jumpStep() {
      this.onlyOnce = false;
      console.log('jumpStep')
      if (!this.operationList.includes('add/edit/del')) {
        if (this.operationList.includes('设置题目')) {
          this.step = 1;
          this.current[0].status = 'finish';
          this.current[1].status = 'process';
        } else {
          if (this.operationList.includes('add/edit/del:stu')) {
            this.step = 2;
            this.current[0].status = 'finish';
            this.current[2].status = 'process';
          }
        }
      }
      if (localStorage.getItem('step')) {
          let next = Number(localStorage.getItem('step'));
          console.log(this.step);
          if (this.step === 0 && this.saveExamMode !== this.examMode) {
            //防止改变考试方式未保存就点击其余步骤
            this.getExamStatus(this.saveExamMode, next);
            this.step = next;
            return;
          }
          this.getExamStatus(this.examMode, next);
          this.step = next;
      }
    },
    getExamInfo(next) {
      this.loading = true;
      this.$http
        .post('/api/design/workexam/getExamInfo', {
          id: this.examid,
        })
        .then((rst) => {
          this.loading = false;
          if (rst.code == 1) {
            rst.info && this.getExamStatus(rst.info.ExamMode, undefined, next);
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    getExamStatus(ExamMode, step, next) {
      if (!(this.$route.name === 'editExamOne' || this.$route.name === 'addExamOne')) {
        if (!(this.$route.name === 'editExamTwo' || this.$route.name === 'addExamTwo')) {
          return;
        }
      }
      this.$http
        .post('/api/design/workexam/getExamStatus', {
          examId: this.examid,
          workexamType: 0,
        })
        .then((rst) => {
          if (rst.code === 1) {
            if (ExamMode === 2) {
              //仅获取数据
              this.isMonitorTea = rst.isMonitorTea;
              this.isMarkTea = rst.isMarkTea;
              this.isPublic = rst.isPublic;
              this.isQues = rst.isQues;
              this.isRoom = rst.isRoom;
              this.isStu = rst.isStu;
              this.isHasBK = rst.isHasBK;
              return;
            }
            this.examMode = ExamMode;
            this.saveExamMode = ExamMode;
            this.step = step ? step : 0;
            this.isMonitorTea = rst.isMonitorTea;
            this.isMarkTea = rst.isMarkTea;
            this.isPublic = rst.isPublic;
            this.isQues = rst.isQues;
            this.isRoom = rst.isRoom;
            this.isStu = rst.isStu;
            this.isHasBK = rst.isHasBK;
            if (ExamMode === 0) {
              //组卷
              this.current = [
                { description: '设置出题人、审核人、分数等考试基本信息', text: this.type, status: 'process' },
                { description: '通过随机出题或手动出题等方式设置考题', text: '设置题目', status: 'wait' }
              ];
            } else {
              //线下
              this.current = [
                { description: '设置出题人、审核人、分数等考试基本信息', text: this.type, status: 'process' },
                { description: '通过随机出题或手动出题等方式设置考题', text: '设置题目', status: 'wait' },
                { description: '从学生管理按班级或个人选择该考试考生', text: '考生导入', status: 'wait' },
                { description: '设置考场、轮次、考场客户端登录教师账号', text: '设置考场', status: 'wait' },
                { description: '选择批阅教师，客观试卷可不设置批阅教师', text: '批阅教师', status: 'wait' },
                { description: '规定考试时间、登录方式、监考手段等规则', text: '发布考试', status: 'wait' },
              ];
              this.current[3].status = rst.isRoom ? 'finish' : 'wait'; //设置考场
              this.current[4].status = rst.isMarkTea ? 'finish' : 'wait'; //批阅教师
              this.current[5].status = rst.isPublic ? 'finish' : 'wait'; //发布考试
            }
            this.current[1].status = rst.isQues ? 'finish' : 'wait'; //设置题目
            
            step !== undefined ? (this.current[0].status = 'finish') : null;
            step !== undefined ? (this.current[step].status = 'process') : null;
            
            this.onlyOnce && this.getOpeartion(); //第一次进页面权限跳转
            next && this.nextStep();
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    initStep(mode) {
      if (mode === 1 && !this.examid) {
        this.examMode = 1;
        this.current = [
          { description: '设置出题人、审核人、分数等考试基本信息', text: this.type, status: 'process' },
          { description: '通过随机出题或手动出题等方式设置考题', text: '设置题目', status: 'wait' },
          { description: '从学生管理按班级或个人选择该考试考生', text: '考生导入', status: 'wait' },
          { description: '设置考场、轮次、考场客户端登录教师账号', text: '设置考场', status: 'wait' },
          { description: '选择批阅教师，客观试卷可不设置批阅教师', text: '批阅教师', status: 'wait' },
          { description: '规定考试时间、登录方式、监考手段等规则', text: '发布考试', status: 'wait' },
        ];
      }
    },
    //步骤条点击
    onChange(next) {
      //没有新建考试时
      if (this.step === 0 && !this.examid) {
        this.$message.warn('请先新建考试');
        return;
      }
      if (next === 0) {
        if (!this.operationList.includes('add/edit/del')) {
          this.$message.warn('您没有此步骤权限！');
          return;
        }
      } else if (this.examid && next === 1) {
        if (!this.operationList.includes('设置题目')) {
          this.$message.warn('您没有此步骤权限！');
          return;
        }
      } else if (this.isQues && next === 2) {
        if (!this.operationList.includes('add/edit/del:stu')) {
          this.$message.warn('您没有此步骤权限！');
          return;
        }
      } else if (this.isStu && next === 3) {
        if (!this.operationList.includes('add/edit/del:room') && !this.operationList.includes('add/edit/del:monitor')) {
          this.$message.warn('您没有此步骤权限！');
          return;
        }
      } else if (next === 4 && (this.isRoom || (this.isStu && this.examMode === 0))) {
        if (!this.operationList.includes('add/edit/del:mark')) {
          this.$message.warn('您没有此步骤权限！');
          return;
        }
      } else if (
        next === 5 &&
        ((this.isStu && this.isQues && this.examid && this.examMode === 0) ||
          (this.isRoom && this.isStu && this.isQues && this.examid && this.examMode === 1))
      ) {
        if (!this.operationList.includes('发布考试')) {
          this.$message.warn('您没有此步骤权限！');
          return;
        }
      } else if (this.current[next].status !== 'finish' && next === this.step + 1) {
        this.$message.warn('完成当前步骤才能点击下一步');
        return;
      } else if (this.current[next].status !== 'finish') {
        this.$message.warn('只能点击已完成的步骤');
        return;
      }
      if (this.step === 0 && this.saveExamMode !== this.examMode) {
        //防止改变考试方式未保存就点击其余步骤
        this.getExamStatus(this.saveExamMode, next);
        this.step = next;
        return;
      }
      this.getExamStatus(this.examMode, next);
      this.step = next;
      localStorage.setItem('step', this.step);
    },
    //下一步
    nextStep() {
      if (this.step + 1 === 1 && !this.operationList.includes('设置题目')) {
        this.$message.warn('您没有下一步步骤权限！');
        return;
      } else if (this.step + 1 === 2 && !this.operationList.includes('add/edit/del:stu')) {
        this.$message.warn('您没有下一步步骤权限！');
        return;
      } else if (
        this.step + 1 === 3 &&
        ((!this.operationList.includes('add/edit/del:room') && this.examMode === 1) ||
          (!this.operationList.includes('add/edit/del:monitor') && this.examMode === 0))
      ) {
        this.$message.warn('您没有下一步步骤权限！');
        return;
      } else if (this.step + 1 === 4 && !this.operationList.includes('add/edit/del:mark')) {
        this.$message.warn('您没有下一步步骤权限！');
        return;
      } else if (this.step + 1 === 5 && !this.operationList.includes('发布考试')) {
        this.$message.warn('您没有下一步步骤权限！');
        return;
      }
      this.getExamStatus(this.examMode, this.step + 1);
      this.step += 1;
      localStorage.setItem('step', this.step);
    },
    //上一步
    previousStep() {
      if (this.step - 1 === 0 && !this.operationList.includes('add/edit/del')) {
        this.$message.warn('您没有上一步步骤权限！');
        return;
      } else if (this.step - 1 === 1 && !this.operationList.includes('设置题目')) {
        this.$message.warn('您没有上一步步骤权限！');
        return;
      } else if (this.step - 1 === 2 && !this.operationList.includes('add/edit/del:stu')) {
        this.$message.warn('您没有上一步步骤权限！');
        return;
      } else if (
        this.step - 1 === 3 &&
        ((!this.operationList.includes('add/edit/del:room') && this.examMode === 1) ||
          (!this.operationList.includes('add/edit/del:monitor') && this.examMode === 0))
      ) {
        this.$message.warn('您没有上一步步骤权限！');
        return;
      } else if (this.step - 1 === 4 && !this.operationList.includes('add/edit/del:mark')) {
        this.$message.warn('您没有上一步步骤权限！');
        return;
      }
      this.getExamStatus(this.examMode, this.step - 1);
      this.step -= 1;
      localStorage.setItem('step', this.step);
    },
    //设置考试方式 渲染对应步骤条
    onChangeExamMode({ target: { value } }) {
      if (this.examid) {
        //有考试id时

        if (this.saveExamMode === 0) {
          //刚进页面存储的临时考试方式，防止未保存刷新

          if (value === 0) {
            //传入的选择值为0，线上考试  与存储的一样为0
            this.getExamStatus(0);
          } else {
            //线下
            this.current = [
              //渲染另一组新建数据
              { description: '设置出题人、审核人、分数等考试基本信息', text: this.type, status: 'process' },
              { description: '通过随机出题或手动出题等方式设置考题', text: '设置题目', status: 'wait' },
              { description: '从学生管理按班级或个人选择该考试考生', text: '考生导入', status: 'wait' },
              { description: '设置考场、轮次、考场客户端登录教师账号', text: '设置考场', status: 'wait' },
              { description: '选择批阅教师，客观试卷可不设置批阅教师', text: '批阅教师', status: 'wait' },
              { description: '规定考试时间、登录方式、监考手段等规则', text: '发布考试', status: 'wait' },
            ];
            this.examMode = 1;
          }
        } else {
          //存储的临时考试为方式为1时，线下考试
          if (value === 0) {
            this.current = [
              { description: '设置出题人、审核人、分数等考试基本信息', text: this.type, status: 'process' },
              { description: '通过随机出题或手动出题等方式设置考题', text: '设置题目', status: 'wait' },
              { description: '从学生管理按班级或个人选择该考试考生', text: '考生导入', status: 'wait' },
              { description: '选择批阅教师，客观试卷可不设置批阅教师', text: '批阅教师', status: 'wait' },
              { description: '规定考试时间、登录方式、监考手段等规则', text: '发布考试', status: 'wait' },
              { description: '分配考生的监考教师，可不设置监考教师', text: '监考教师', status: 'wait' },
            ];
            this.examMode = 0;
          } else {
            this.getExamStatus(1);
          }
        }
      } else {
        //新建时
        if (value === 0) {
          this.current = [
            { description: '设置出题人、审核人、分数等考试基本信息', text: this.type, status: 'process' },
            { description: '通过随机出题或手动出题等方式设置考题', text: '设置题目', status: 'wait' },
            { description: '从学生管理按班级或个人选择该考试考生', text: '考生导入', status: 'wait' },
            { description: '选择批阅教师，客观试卷可不设置批阅教师', text: '批阅教师', status: 'wait' },
            { description: '规定考试时间、登录方式、监考手段等规则', text: '发布考试', status: 'wait' },
            { description: '分配考生的监考教师，可不设置监考教师', text: '监考教师', status: 'wait' },
          ];
          this.examMode = 0;
        } else {
          this.current = [
            { description: '设置出题人、审核人、分数等考试基本信息', text: this.type, status: 'process' },
            { description: '通过随机出题或手动出题等方式设置考题', text: '设置题目', status: 'wait' },
            { description: '从学生管理按班级或个人选择该考试考生', text: '考生导入', status: 'wait' },
            { description: '设置考场、轮次、考场客户端登录教师账号', text: '设置考场', status: 'wait' },
            { description: '选择批阅教师，客观试卷可不设置批阅教师', text: '批阅教师', status: 'wait' },
            { description: '规定考试时间、登录方式、监考手段等规则', text: '发布考试', status: 'wait' },
          ];
          this.examMode = 1;
        }
      }
    },
    getExamData(examData) {
      this.examData = examData;
    },
    changeReviewPaper(val) {
      this.$refs.reviewPaper.getPaperIndex(val);
    },
  },
};
</script>

<style lang="scss">
// .ant-steps-item-process>.ant-steps-item-container>.ant-steps-item-content>.ant-steps-item-description,
// .ant-steps-item-finish>.ant-steps-item-container>.ant-steps-item-content>.ant-steps-item-description{
//   max-width: 100%;
// }
</style>